package com.haople.sso.client.spring.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.haople.sso.client.SsoClient;
import com.haople.sso.client.service.TicketValidateService;
import com.haople.sso.core.service.CookieService;
import com.haople.sso.core.vo.Ticket;

public class ClientInterceptor  implements HandlerInterceptor,SsoClient {

	@Autowired
	private TicketValidateService ticketValidateService;
	@Autowired
	private CookieService cookieService;
	
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
			
	}
	
	/**
	 * 验证票据
	 */
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView modelAndView)
			throws Exception {
		HttpSession	httpSession=request.getSession();
		String userId=null;
		String ticketValue=null;
		//从cookie中获取票据信息（userId，ticket）
		Ticket ticket=cookieService.getTicket(request.getCookies());
		if(ticket!=null){
			userId=ticket.getUserId();
			ticketValue=ticket.getTicket();
		}
		if(StringUtils.isEmpty(ticketValue) || StringUtils.isEmpty(userId)){ //如果值依然为空
			String service=request.getRequestURL().toString();
			String loginUrl=ticketValidateService.getLoginUrl();
			response.sendRedirect(loginUrl+"?service="+service);
			return;
		}
		final String currentTicket=userId+"|"+ticketValue;
		String sessionTicket=null;
		if(!StringUtils.isEmpty(httpSession.getAttribute(SSO_CLIENT_SESSION))){
			sessionTicket=String.valueOf(httpSession.getAttribute(SSO_CLIENT_SESSION));
		}
		if(sessionTicket==null || (sessionTicket!=null && !sessionTicket.equals(currentTicket))) {
			//验证票据有效性
			boolean flag=ticketValidateService.ticketValidate(userId, ticketValue);
			if(!flag){ //如果验证时失败
				String service=request.getRequestURL().toString();
				String loginUrl=ticketValidateService.getLoginUrl();
				response.sendRedirect(loginUrl+"?service="+service);
				return;
			}else{
				httpSession.setAttribute(SSO_CLIENT_SESSION, currentTicket);
			}
		}
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		return true;
	}

}
